#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QHostAddress>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    udpSocket = new QUdpSocket(this);
    udpSocket->bind(QHostAddress(QHostAddress::Any), 5555, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint);
    connect(udpSocket, SIGNAL(readyRead()), this, SLOT(slotReadyRead()));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::slotReadyRead()
{
    QByteArray bytes;
    while(udpSocket->hasPendingDatagrams()){
        int maxSize = udpSocket->pendingDatagramSize();
        char udpData[maxSize] = {0};
        udpSocket->readDatagram(udpData, maxSize);
        bytes.append(QByteArray(udpData, maxSize));
    }
    ui->textBrowser->append(QString::fromUtf8(bytes));
}

void MainWindow::on_pushButton_clicked()
{
    QString message = "程老师说: " + ui->lineEdit->text();
    udpSocket->writeDatagram(message.toUtf8().data(), QHostAddress(QHostAddress::Broadcast), 5555);
}
